package com.www.applyword.ui.home;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.adapter.GirdDropDownAdpter;
import com.www.applyword.adapter.GirdDropDownAdpter2;
import com.www.applyword.base.BaseActivity;
import com.www.applyword.base.BaseFragment;
import com.www.applyword.bean.AllCityBean;
import com.www.applyword.bean.AllPositionListBean;
import com.www.applyword.event.EventConstants;
import com.www.applyword.event.MessageEvent;
import com.www.applyword.fragment.OrderSettlementFragment;
import com.www.applyword.fragment.OrderSettlementFragment2;
import com.www.applyword.fragment.OrderSettlementFragment3;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;
import com.www.applyword.view.CustomPopWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author : huang
 * date   : 2019/10/25 0025 17:29
 * version: 1.0
 *
 * @author Administrator
 */
public class WordPositionActivity extends BaseActivity {
    @BindView(R.id.tablayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_job)
    TextView tvJob;
    @BindView(R.id.tv_dic)
    TextView tvDic;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_comprehensive)
    TextView tvComprehensive;


    private CustomPopWindow mPopWindow,mPopWindow2,mPopWindow4;
    public CustomPopWindow mPopWindow3;


    private List<View> popupViews = new ArrayList<>();
    private List<BaseFragment> fragments = new ArrayList<>();
    private List<String> tabs = new ArrayList<>();
    private List<String> citys = new ArrayList<>();
    private List<AllPositionListBean> allPositionListBeans2 = new ArrayList<>();
    private String headers[] = {"离我最近", "最新发布"};
   // private String citys[] = {"江岸区", "江汉区", "硚口区", "汉阳区", "武昌区", "青山区", "洪山区", "东西湖区", "汉南区"};
    private String areaId;
    private String sex;
    private String city;


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.word_position_activity);
        setTitle("职位");
        Constants.flag = false;

      //  Utils.showToastSafe(Constants.flag + "");
        initView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private void initView() {
        int position =  getIntent().getIntExtra("position", 0);
        city = getIntent().getStringExtra("city");
        if (!TextUtils.isEmpty(city)){
            tvCity.setText("全" + city);
            if (city.contains("武汉")){
                SPUtil.put("city2", "");
            }else {
                SPUtil.put("city2", city);
            }
        }else {
            SPUtil.put("city2", "");
        }
        fragments.clear();
        tabs.clear();
        tabs.add("小时结");
        tabs.add("日结");
        tabs.add("月结");
        fragments.add(new OrderSettlementFragment());
        fragments.add(new OrderSettlementFragment2());
        fragments.add(new OrderSettlementFragment3());

        //设置TabLayout的模式
        viewPager.setAdapter(new TabAdapter(getSupportFragmentManager()));
        //关联ViewPager和TabLayout
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(position);
        //viewpaer一次加载全部页面
        viewPager.setOffscreenPageLimit(fragments.size());
    }

    @Override
    protected void onResume() {
        super.onResume();
        city = getIntent().getStringExtra("city");
        String json  = SPUtil.getString("json");
        if (!TextUtils.isEmpty(json)){
            List<AllCityBean> allCityBean = new Gson().fromJson(json, new TypeToken<List<AllCityBean>>(){}.getType());
          //  List<AllCityBean> allCityBean = (List<AllCityBean>) new Gson().fromJson(json, AllCityBean.class);
            if (null != allCityBean && allCityBean.size() > 0)
            if (!TextUtils.isEmpty(city)){
                for (AllCityBean cityBean : allCityBean) {
                    if (!TextUtils.isEmpty(cityBean.getAreaName())) {
                        if (cityBean.getAreaName().contains(city)) {
                            //武汉市id
                            areaId = cityBean.getAreaId();
                            getAreaList(areaId);
                        }
                    }
                }
            }else {
                String city = SPUtil.getString("city");
                for (AllCityBean cityBean : allCityBean) {
                    if (!TextUtils.isEmpty(cityBean.getAreaName())) {
                        if (cityBean.getAreaName().contains(city)) {
                            //武汉市id
                            areaId = cityBean.getAreaId();
                            getAreaList(areaId);
                        }
                    }
                }
            }
            return;
        }
        Map<String, Object> params = new HashMap<>();
        HttpClient.get(WordPositionActivity.this, Constants.GETALLCITY, params,new CallBack<List<AllCityBean>>() {
            @Override
            public void onSuccess(List<AllCityBean> allCityBean) {
                if (!TextUtils.isEmpty(city)){
                    for (AllCityBean cityBean : allCityBean) {
                        if (cityBean.getAreaName().contains(city)){
                            //武汉市id
                            areaId = cityBean.getAreaId();
                            getAreaList(areaId);
                        }
                    }
                }else {
                    String city = SPUtil.getString("city");
                    for (AllCityBean cityBean : allCityBean) {
                        if (cityBean.getAreaName().contains(city)){
                            //武汉市id
                            areaId = cityBean.getAreaId();
                            getAreaList(areaId);
                        }
                    }
                }
            }
        });
    }

    /* @Override
    public void finish() {
        super.finish();
      //  overridePendingTransition(R.anim.push_top_out, R.anim.push_top_in);
    }*/

    @Override
    protected void loadData() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessageKey() != null) {
            if (messageEvent.getMessageKey().equals(EventConstants.POSITION)) {
                mPopWindow3.dissmiss();
            }
        }
    }

    private void getAreaList(String areaId) {
        Map<String, Object> params = new HashMap<>();
        params.put("ParentID",areaId);
        HttpClient.get(WordPositionActivity.this, Constants.GETAREALIST, params,new CallBack<List<AllCityBean>>() {
            @Override
            public void onSuccess(List<AllCityBean> allCityBean) {
                citys.clear();
                for (AllCityBean cityBean : allCityBean) {
                   citys.add(cityBean.getAreaName());
                }
            }
        });
        getAllPositionList();
    }

    //职位
    private void getAllPositionList() {
        Map<String, Object> params = new HashMap<>();
        HttpClient.get(WordPositionActivity.this, Constants.GETALLPOSITIONLIST, params,new CallBack<List<AllPositionListBean>>() {
            @Override
            public void onSuccess(List<AllPositionListBean> allPositionListBeans) {
                allPositionListBeans2.clear();
                allPositionListBeans2.addAll(allPositionListBeans);
            }
        });
    }


    @OnClick({R.id.tv_city, R.id.tv_job, R.id.tv_dic, R.id.tv_comprehensive})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_city:
                showCityInfo();
                break;
            case R.id.tv_job:
                showPositionInfo();
                break;
            case R.id.tv_dic:
                showDicInfo();
                break;
            case R.id.tv_comprehensive:
                //综合筛选
                showSynthesisInfo();
                break;
                default:
        }
    }

    //职位
    private void showPositionInfo() {
        final ListView cityView = new ListView(this);
        GirdDropDownAdpter2 cityAdapter = new GirdDropDownAdpter2(this, allPositionListBeans2);
        cityView.setDividerHeight(0);
        cityView.setAdapter(cityAdapter);

        int popWindowWidth = (int) (Utils.getDeviceDensity().widthPixels);
        int popWindowHeight = (int) (Utils.getDeviceDensity().heightPixels);

        mPopWindow3 = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(cityView)
                .size(popWindowWidth, popWindowHeight)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .enableBackgroundDark(true)
                .setBgDarkAlpha((float) 0.4)
                .create();
        mPopWindow3.showAsDropDown(ll, 0, 20);
    }

    private void showSynthesisInfo() {
            View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_synthesis, null);
            int popWindowWidth = (int) (Utils.getDeviceDensity().widthPixels);
           // int popWindowHeight = 500;
            int popWindowHeight = (int) (Utils.getDeviceDensity().heightPixels/2);
              RadioGroup rgSex = contentView.findViewById(R.id.rg_sex);
              RadioButton rbAll = contentView.findViewById(R.id.rb_all);
              RadioButton rb_unlimited = contentView.findViewById(R.id.rb_unlimited);
              Button bt_1 = contentView.findViewById(R.id.bt_1);
              Button bt_2 = contentView.findViewById(R.id.bt_2);
              rbAll.setChecked(true);
              rb_unlimited.setChecked(true);
              bt_2.setOnClickListener(v -> {
                  MessageEvent messageEvent = new MessageEvent();
                  messageEvent.setMessageKey(EventConstants.SEX);
                  messageEvent.setMessageValue(sex);
                  EventBus.getDefault().post(messageEvent);
                  mPopWindow4.dissmiss();
              });

             rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                 @Override
                 public void onCheckedChanged(RadioGroup group, int checkedId) {
                     int position = group.indexOfChild(group.findViewById(checkedId));
                     if (position == 0){
                         sex = "女";
                     }else if (position == 1){
                          sex = "男";
                     }else {
                          sex = "";
                     }
                 }
             });

              bt_1.setOnClickListener(v -> {
                  rbAll.setChecked(true);
                  rb_unlimited.setChecked(true);
              });

            mPopWindow4 = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(contentView)
                    .size(popWindowWidth, popWindowHeight)
                    .setFocusable(true)
                    .setOutsideTouchable(true)
                    .enableBackgroundDark(true)
                    .setBgDarkAlpha((float) 0.4)
                    .create();
        mPopWindow4.showAsDropDown(ll);
    }

    private void showDicInfo() {
        final ListView cityView = new ListView(this);
        GirdDropDownAdpter cityAdapter = new GirdDropDownAdpter(this, Arrays.asList(headers));
        cityView.setDividerHeight(0);
        cityView.setAdapter(cityAdapter);

        cityView.setOnItemClickListener((parent, view, position, id) -> {
            MessageEvent messageEvent = new MessageEvent();
            messageEvent.setMessageKey(EventConstants.DIC);
            messageEvent.setMessageValue(headers[position]);
            EventBus.getDefault().post(messageEvent);
            mPopWindow2.dissmiss();
        });

            int popWindowWidth = (int) (Utils.getDeviceDensity().widthPixels);
            int popWindowHeight = (int) (Utils.getDeviceDensity().heightPixels);

            mPopWindow2 = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(cityView)
                    .size(popWindowWidth, popWindowHeight)
                    .setFocusable(true)
                    .setOutsideTouchable(true)
                    .enableBackgroundDark(true)
                    .setBgDarkAlpha((float) 0.4)
                    .create();
        mPopWindow2.showAsDropDown(ll, 0, 20);
    }

    //获取城市
    private void showCityInfo() {
        final ListView cityView = new ListView(this);
        GirdDropDownAdpter cityAdapter = new GirdDropDownAdpter(this, citys);
        cityView.setDividerHeight(0);
        cityView.setAdapter(cityAdapter);

        cityView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              //  Utils.showToastSafe(citys.get(position));
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.CITY);
                messageEvent.setMessageValue(citys.get(position));
                EventBus.getDefault().post(messageEvent);
                mPopWindow.dissmiss();
            }
        });

            int popWindowWidth = (int) (Utils.getDeviceDensity().widthPixels);
            int popWindowHeight = (int) (Utils.getDeviceDensity().heightPixels);

            mPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(cityView)
                    .size(popWindowWidth, popWindowHeight)
                    .setFocusable(true)
                    .setOutsideTouchable(true)
                    .enableBackgroundDark(true)
                    .setBgDarkAlpha((float) 0.4)
                    .create();
        mPopWindow.showAsDropDown(ll, 0, 20);
    }

    private void setBackgroundAlpha(float v) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = v;
        getWindow().setAttributes(lp);
    }


    class TabAdapter extends FragmentPagerAdapter {
        public TabAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        //显示标签上的文字
        @Override
        public CharSequence getPageTitle(int position) {
            return tabs.get(position);
        }
    }
}
